package com.finance.capacity.capacitySummary.controller;

import com.finance.base.constant.BaseConstants;
import com.finance.base.enums.CapSiteDetailStatusEnum;
import com.finance.base.exception.BaseException;
import com.finance.capacity.capacityMaintain.request.MaintainListReq;
import com.finance.capacity.capacitySummary.request.CapSummaryReq;
import com.finance.capacity.casualDetail.bean.pojo.CasualDetailList;
import com.finance.capacity.casualDetail.capService.ICasualDetailService;
import com.finance.capacity.common.capService.ICapOrganizationService;
import com.finance.capacity.deliveryDetail.bean.pojo.DeliveryDetailErr;
import com.finance.capacity.deliveryDetail.bean.pojo.DeliveryDetailList;
import com.finance.capacity.deliveryDetail.capService.IDeliveryDetailService;
import com.finance.capacity.siteCoefficientDaily.bean.pojo.SiteCoeDaily;
import com.finance.capacity.siteCoefficientDaily.capService.ISiteCoefficientDailyService;
import com.finance.capacity.siteDetail.bean.pojo.SiteDetail;
import com.finance.capacity.siteDetail.bean.pojo.SiteDetailList;
import com.finance.capacity.siteDetail.capService.ISiteDetailService;
import com.finance.capacity.siteDetailLog.bean.pojo.SiteDetailLog;
import com.finance.capacity.siteDetailLog.capService.ISiteDetailLogService;
import com.finance.framework.controller.BaseController;
import com.finance.framework.controller.Result;
import com.finance.framework.lang.Page;
import com.finance.framework.lang.PageResultBO;
import com.finance.system.bean.pojo.User;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @Author: gly
 * @Date: Created in 2017-05-23
 */
@Controller
@RequestMapping("/capacity/capsummary")
public class CapSummaryController extends BaseController {
    @Resource
    private ISiteDetailService siteDetailService;

    @Resource
    private IDeliveryDetailService deliveryDetailService;

    @Resource
    private ICasualDetailService casualDetailService;

    @Resource
    private ICapOrganizationService capOrganizationService;

    @Resource
    private ISiteDetailLogService siteDetailLogService;

    @Resource
    private ISiteCoefficientDailyService siteCoefficientDailyService;

    /**
     * 站点运力详情分页展示列表
     *
     * @param form
     * @return
     */
    @RequestMapping("/listall")
    public Result list(CapSummaryReq form) {
        Page page = Page.getInstance(form);
        SiteDetailList siteDetailList = new SiteDetailList();
        siteDetailList.setProvinceId(form.getProvinceId());
        siteDetailList.setCityId(form.getCityId());
        siteDetailList.setSiteId(form.getSiteId());
        siteDetailList.setBeginTime(form.getBeginTime());
        siteDetailList.setEndTime(form.getEndTime());
        if (StringUtils.isNotBlank(form.getKeyWords())) {
            List<String> keyWordsList = new ArrayList<String>();
            List<String> names = Arrays.asList(form.getKeyWords().split("、"));
            for (String orgName : names) {
                List<String> orgCodes = capOrganizationService.getIdByName(orgName);
                if (orgCodes != null && orgCodes.size() > 0) {
                    keyWordsList.addAll(orgCodes);
                } else {
                    orgCodes.add("no_site");
                    keyWordsList.addAll(orgCodes);
                }
            }
            siteDetailList.setKeyWords(keyWordsList);

        }
        if (StringUtils.isNotBlank(form.getStatusStr())) {
            List<String> statusStrList = Arrays.asList(form.getStatusStr().split(","));
            siteDetailList.setStatusStr((statusStrList));
        }
        page.setParams(siteDetailList);
        PageResultBO<SiteDetail> resultBO = siteDetailService.capSummaryListByPage(page);
        return getSuccessResult(resultBO);
    }

    @RequestMapping("/exportall")
    public Result exportSummaryList(CapSummaryReq form, HttpServletResponse response) throws UnsupportedEncodingException {
        if (StringUtils.isBlank(form.getBeginTime()) || StringUtils.isBlank(form.getEndTime())) {
            throw new BaseException(BaseConstants.ERR_PARAMETER_IS_NULL);
        }
        SiteDetailList siteDetailList = new SiteDetailList();
        siteDetailList.setProvinceId(form.getProvinceId());
        siteDetailList.setCityId(form.getCityId());
        siteDetailList.setSiteId(form.getSiteId());
        siteDetailList.setBeginTime(form.getBeginTime());
        siteDetailList.setEndTime(form.getEndTime());
        if (StringUtils.isNotBlank(form.getKeyWords())) {
            List<String> keyWordsList = new ArrayList<String>();
            List<String> names = Arrays.asList(form.getKeyWords().split("、"));
            for (String orgName : names) {
                List<String> orgCodes = capOrganizationService.getIdByName(orgName);
                if (orgCodes != null && orgCodes.size() > 0) {
                    keyWordsList.addAll(orgCodes);
                } else {
                    orgCodes.add("no_site");
                    keyWordsList.addAll(orgCodes);
                }
            }
            siteDetailList.setKeyWords(keyWordsList);
        }
        if (StringUtils.isNotBlank(form.getStatusStr())) {
            List<String> statusStrList = Arrays.asList(form.getStatusStr().split(","));
            siteDetailList.setStatusStr((statusStrList));
        }
        List<SiteDetail> exportCapSummary = siteDetailService.exportSummaryList(siteDetailList);
        if (exportCapSummary != null && exportCapSummary.size() > 0) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
            String fileName = "所有站点汇总运力报表" + sdf.format(new Date());
            String suffix = ".xls";
            fileName = fileName + suffix;
            // 声明一个工作簿
            HSSFWorkbook workbook = new HSSFWorkbook();
            // 生成一个表格
            HSSFSheet sheet = workbook.createSheet("运力汇总列表");
            sheet.createDrawingPatriarch();
            HSSFRow row = sheet.createRow(0);
            String[] titles = new String[]{"序号", "省公司", "市公司", "站点", "总单量", "人效单量", "出勤人数", "站点人效", "日期", "状态"};
            for (int i = 0; i < titles.length; i++) {
                HSSFCell cell = row.createCell(i);
                cell.setCellValue(titles[i]);
            }
            for (int i = 0; i < exportCapSummary.size(); i++) {
                SiteDetail siteDetail = (SiteDetail) exportCapSummary.get(i);
                row = sheet.createRow(i + 1);
                row.createCell(0).setCellValue(i + 1);
                row.createCell(1).setCellValue(siteDetail.getProvinceName());
                row.createCell(2).setCellValue(siteDetail.getCityName());
                row.createCell(3).setCellValue(siteDetail.getSiteName());
                row.createCell(4).setCellValue(siteDetail.getOrderTotalNum());
                row.createCell(5).setCellValue(siteDetail.getOrderEfficiencyNum());
                row.createCell(6).setCellValue(siteDetail.getWorkerNum());
                row.createCell(7).setCellValue(String.valueOf(siteDetail.getSiteEfficiency()));
                row.createCell(8).setCellValue(siteDetail.getSiteDate());
                row.createCell(9).setCellValue(siteDetail.getStatus() == 1 ? "已修改" : siteDetail.getStatus() == 2 ? "已审核" : "已提交");
            }
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            ServletOutputStream outputStream;
            try {
                outputStream = response.getOutputStream();
                workbook.write(outputStream);
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
                return getFailResult(BaseConstants.ERR_UNKOWN, e.getMessage());
            }
            return getSuccessResult("导出成功");
        } else {
            return getFailResult(BaseConstants.ERR_RESULT_NULL, BaseConstants.getErrorMessage(BaseConstants.ERR_RESULT_NULL));
        }

    }

    @RequestMapping("/list")
    public Result siteCapDetail(String siteId, String siteDate) {
        if (StringUtils.isBlank(siteId) || StringUtils.isBlank(siteDate)) {
            return getFailResult(BaseConstants.ERR_INVALID_PARAMETER, BaseConstants.getErrorMessage(BaseConstants.ERR_INVALID_PARAMETER));
        }

        List<SiteDetail> siteDetails = null;
        try {
            siteDetails = siteDetailService.siteCapDetail(siteId, siteDate);
        } catch (Exception e) {
            e.printStackTrace();
            return getFailResult(BaseConstants.ERR_SQL_EXCUTE_NULL, BaseConstants.getErrorMessage(BaseConstants.ERR_SQL_EXCUTE_NULL));
        }
        if (siteDetails == null || siteDetails.size() == 0) {
            return getFailResult(BaseConstants.ERR_RESULT_NULL, BaseConstants.getErrorMessage(BaseConstants.ERR_RESULT_NULL));
        }
        return getSuccessResult(siteDetails);
    }

    @RequestMapping("/deliverycap")
    public Result deliveryCap(String relationId) {
        if (StringUtils.isBlank(relationId)) {
            return getFailResult(BaseConstants.ERR_INVALID_PARAMETER, BaseConstants.getErrorMessage(BaseConstants.ERR_INVALID_PARAMETER));
        }
        List<DeliveryDetailList> deliveryDetailLists = null;
        try {
            deliveryDetailLists = deliveryDetailService.deliveryCapDetail(relationId);
        } catch (Exception e) {
            e.printStackTrace();
            return getFailResult(BaseConstants.ERR_SQL_EXCUTE_NULL, BaseConstants.getErrorMessage(BaseConstants.ERR_SQL_EXCUTE_NULL));
        }

        return getSuccessResult(deliveryDetailLists);
    }

    @RequestMapping("/casualcap")
    public Result casualCap(String relationId) {
        if (StringUtils.isBlank(relationId)) {
            return getFailResult(BaseConstants.ERR_INVALID_PARAMETER, BaseConstants.getErrorMessage(BaseConstants.ERR_INVALID_PARAMETER));
        }
        List<CasualDetailList> casualDetailLists = null;
        try {
            casualDetailLists = casualDetailService.casualCapDetail(relationId);
        } catch (Exception e) {
            e.printStackTrace();
            return getFailResult(BaseConstants.ERR_SQL_EXCUTE_NULL, BaseConstants.getErrorMessage(BaseConstants.ERR_SQL_EXCUTE_NULL));
        }
        return getSuccessResult(casualDetailLists);
    }

    @RequestMapping("/update")
    public Result update(String datas) {
        if (StringUtils.isBlank(datas)) {
            return getFailResult(BaseConstants.ERR_PARAMS_NULL, BaseConstants.getErrorMessage(BaseConstants.ERR_PARAMS_NULL));
        }
        User user = getAuthUser();
        if (user == null) {
            return getFailResult(BaseConstants.ERR_UNKONW_USER, BaseConstants.getErrorMessage(BaseConstants.ERR_UNKONW_USER));
        }
        List<DeliveryDetailErr> deliveryDetailErrs = deliveryDetailService.summaryDeliveryModify(datas, user);
        return getSuccessResult(deliveryDetailErrs);
    }

    @RequestMapping("/check")
    public Result check(String siteDetailId) {
        if (StringUtils.isBlank(siteDetailId)) {
            return getFailResult(BaseConstants.ERR_PARAMS_NULL, BaseConstants.getErrorMessage(BaseConstants.ERR_PARAMS_NULL));
        }
        User user = getAuthUser();
        if (user == null) {
            return getFailResult(BaseConstants.ERR_UNKONW_USER, BaseConstants.getErrorMessage(BaseConstants.ERR_UNKONW_USER));
        }
        String updateUid = String.valueOf(user.getId());
        int status = CapSiteDetailStatusEnum.audit.getStatus();
        SiteDetailList siteDetail = siteDetailService.getSiteDetailById(Long.valueOf(siteDetailId));
        SiteCoeDaily siteCoeDaily =new SiteCoeDaily();
        if(siteDetail!=null){
            siteCoeDaily.setProvinceId(siteDetail.getProvinceId());
            siteCoeDaily.setCityId(siteDetail.getCityId());
            siteCoeDaily.setSiteId(siteDetail.getSiteId());
            siteCoeDaily.setRelationId(Long.valueOf(siteDetailId));
            siteCoeDaily.setOrderEfficientNum(siteDetail.getOrderEfficiencyNum());
            siteCoeDaily.setWorkerNum(siteDetail.getWorkerNum());
            siteCoeDaily.setSiteDate(siteDetail.getSiteDate());
            BigDecimal avgNum =siteDetailService.getAvgEffOrderNum(siteDetailId,siteDetail.getSiteDate());
            BigDecimal avgMoreNum = siteDetailService.getMoreAvgEffOrderNum(siteDetailId,siteDetail.getSiteDate(),avgNum);
            BigDecimal avgLessNum = siteDetailService.getLessAvgEffOrderNum(siteDetailId,siteDetail.getSiteDate(),avgNum);
            if(avgNum.compareTo(BigDecimal.ZERO)==0) {
                siteCoeDaily.setCoefficient(BigDecimal.valueOf(0.00));
            }else{
                BigDecimal coefficient = avgMoreNum.subtract(avgLessNum).divide(avgNum,2, RoundingMode.HALF_UP);
                siteCoeDaily.setCoefficient(coefficient);
            }
            siteCoeDaily.setCreateUid(user.getId());
            siteCoefficientDailyService.add(siteCoeDaily);
            siteDetailService.checkSiteDetail(siteDetailId, updateUid, status);
        }else{
            return getFailResult(BaseConstants.ERR_FAIL,"没有找到ID对应的站点运力详情记录");
        }

        return getSuccessResult("审核成功");
    }

    @RequestMapping("/sitelogs")
    public Result getSiteLogList(MaintainListReq form) {
        if (StringUtils.isBlank(form.getSiteDetailId())) {
            return getFailResult(BaseConstants.ERR_PARAMS_NULL, BaseConstants.getErrorMessage(BaseConstants.ERR_PARAMS_NULL));
        }
        List<SiteDetailLog> siteDetailLogs = siteDetailLogService.getSiteLog(form.getSiteDetailId());
        return getSuccessResult(siteDetailLogs);
    }


}
